import { action, observable, toJS } from "mobx";
import { WeaForm } from "comsMobx";
import * as API from "../../apis/card";
import { message } from "antd";
import { condition, detailCondition } from "../data/logList";
import IndexAPI from '../../apis';
import _ from "lodash";
import { WeaLocaleProvider } from "ecCom";
const getLabel = WeaLocaleProvider.getLabel;

export class LogListStore {
    @observable form = new WeaForm();
    @observable detailFrom = new WeaForm();
    @observable loading: boolean = false;
    @observable title: string = "日志";
    @observable tableData = {
        total: 0,
        logData: [],
    };
    modeId:string;
    @observable logDetailTableData = {
        logDataDetail: [],
        detailTotal: 0
    }
    @observable showSearchAd: boolean = false;
    @observable condition: any[] = [];
    @observable detailCondition: any = [];
    @observable baseParams: any = {};
    @observable isBackLog: boolean = false;
    @observable logid: any = '';
    detailBaseParams: any = {};
    @observable checkValues: any = {
        munedit: "1",
        create: "1",
        view: "0",
        edit: "1",
        delete:'1',
        recover:'1'
    }
    @observable table: any = {
        current: 1,
        pagesize: 10
    }
    @observable detailTable: any = {
        current: 1,
        pagesize: 10
    }
    @observable visible: boolean = false;
    @observable mainLog_visible: boolean = false;
    @observable delLog_visible: boolean = false;
    @observable detailLog_visible: boolean = false;
    @observable currentType: any = '';
    @observable mainLog_data;
    @observable detailLog_data;
    @observable dialog: any = {
        loading: false,
        loadingTips: "正在加载中...",
        title: ""
    }
    @observable iconInfo = {
        icon: "icon-coms-ModelingEngine",
        iconColor: "#fff",
        iconBg: "#96358a"
    }
    @observable operateButton=[];

    @action
    updateParams = (params: any) => {
        this.isBackLog='back'==params.logtype;
        if(this.isBackLog){
            this.checkValues.view="1";
        }
        this.condition = condition( this.isBackLog);
        this.detailCondition = detailCondition();
        this.title = getLabel(83, '日志');
        this.dialog = {
            loading: false,
            loadingTips: getLabel(124820, "正在加载中..."),
            title: ""
        }
        this.form && !this.form.isFormInit && this.form.initFormFields(toJS(this.condition));
        this.title =  decodeURIComponent(params.modename);
        this.setOperateTypeValue(params);
        delete params.modename;
        delete params.guid;
        this.search({ ...this.checkValues, ...params });
        this.baseParams = { ...params };
        this.modeId=params.modeId;
        this.getIconInfo(params.modeId);
    }

    @action
    setShowSearchAd = (bool: boolean) => {
        this.showSearchAd = bool;
    }

    setOperateTypeValue = (params)=>{
        let checkValues={};
        if(params.operatetype){//自定义操作类型值
            let operates=params.operatetype.split(',');
            if(operates.length>=4){
                checkValues['create']=operates[0];
                checkValues['edit']=operates[1];
                checkValues['view']=operates[2];
                checkValues['munedit']=operates[3];
                this.checkValues={...this.checkValues,...checkValues}
            }
        }
    }
    @action
    clearFormFields = () => {
        this.form.resetConditionValue();      //清除查询条件值
        this.checkValues = {
            munedit: "1",
            create: "1",
            view: "0",
            edit: "1"
        }
        if(this.isBackLog){
            this.checkValues.delete="1";
            this.checkValues.view="1";
            this.checkValues.recover="1";
        }
        this.setOperateTypeValue( this.baseParams);
    }

    @action
    onCheckGroupChange = (checkedValue) => {
        let newObj: any = {};
        _.each(checkedValue, (data: string) => {
            newObj[data] = "1";
        });
        const checkValues = { munedit: "0", create: "0", view: "0", edit: "0", ...newObj };
        this.checkValues = checkValues;
    }

    @action
    doSearch = (params: any = {}) => {
        const searchParamsAd = this.form.getFormParams();
        const newParams = { ...this.table, ...this.baseParams, ...this.checkValues, ...searchParamsAd, ...params };
        this.search(newParams);
    }

    @action
    recoverData = () => {
        API.recoverData({logid:this.logid,modeid:this.modeId}).then(({ api_status, api_errormsg, noRight,status }) => {
            this.delLog_visible=false;
            if(noRight){
                message.error(getLabel(2012,'对不起，您暂时没有权限！'))
            }
            if (api_status) {
                if(status=='1'){
                    message.info(getLabel('522825','数据恢复成功') )
                }else if(status=='0'){
                    message.error(getLabel('522827','该数据在数据库中已存在,无法恢复')   )
                }else{
                    message.error(getLabel('522826','数据恢复失败')  )
                }
                this.doSearch();
            } else {
                message.error(getLabel(383746, '请求失败') + "：" + api_errormsg)
            }
        });
    }

    @action
    search = (params: any) => {
        API.getCardLog(params).then(({ api_status, api_errormsg, total, logData,orderList }) => {
            if (api_status) {
                //对操作类型进行多语言转化
                let newLogData = logData.map(element =>{
                    // switch (element.operatetype) {
                    //     case '1': element.operatedesc = getLabel(82, "新建"); break;
                    //     case '2': element.operatedesc = getLabel(103, "修改"); break;
                    //     case '3': element.operatedesc = getLabel(91, "删除"); break;
                    //     case '5': element.operatedesc = getLabel(25465,"批量修改") ;break;
                    // }
                    return element;
                });

                this.tableData = {
                    total: total,
                    logData: newLogData
                }
                if(orderList){
                    this.operateButton=orderList;
                }
            } else {
                message.error(getLabel(383746, '请求失败') + "：" + api_errormsg)
            }
        });
    }

    @action
    changePageSize = (current, pagesize) => {
        this.table = {
            current: current,
            pagesize: pagesize
        };
        this.doSearch({ current: current, pagesize: pagesize });
    }

    @action
    nextDatas = (pagination) => {
        let current = pagination.current;
        this.table = {
            ...this.table,
            current: current
        };
        this.doSearch({ current: current });
    }

    @action
    objToArr = (obj) => {
        let item: any = [];
        _.each(obj, (value, key) => {
            if (value == "1") {
                item.push(key);
            }
        })
        return item;
    }

    @action
    onCancel = () => {
        this.visible = false;
        this.detailTable = {
            current: 1,
            pagesize: 10
        }
    }

    @action
    showCodeAllLog = (id: string, name: string, ) => {
        this.visible = true;
        this.dialog = {
            ...this.dialog,
            loading: true,
            title: name
        };
        this.detailFrom = new WeaForm();
        this.detailFrom && !this.detailFrom.isFormInit && this.detailFrom.initFormFields(toJS(this.detailCondition));
        this.detailBaseParams = { fieldid: id };
        this.searchDetail({ ...this.detailTable, ...this.baseParams, fieldid: id });
    }

    @action
    searchDetail = (params: any) => {
        this.dialog = {
            ...this.dialog,
            loading: true
        };
        API.getCardLogDetail(params).then(({ api_status, api_errormsg, logDataDetail, detailTotal }) => {
            if (api_status) {
                this.logDetailTableData = {
                    logDataDetail: logDataDetail,
                    detailTotal: detailTotal
                }
                this.dialog = {
                    ...this.dialog,
                    loading: false
                };
            } else {
                message.error(getLabel(383746, '请求失败') + "：" + api_errormsg)
            }
        });
    }
    @action
    doDetailSearch = (params: any = {}) => {
        const detailSearchParamsAd = this.detailFrom.getFormParams();
        const newParams = { ...this.detailTable, ...this.baseParams, ...this.detailBaseParams, ...detailSearchParamsAd, ...params };
        this.searchDetail(newParams);
    }
    @action
    changeDetailPageSize = (current, pagesize) => {
        this.detailTable = {
            current: current,
            pagesize: pagesize
        };
        this.doDetailSearch({ current: current, pagesize: pagesize });
    }
    @action
    nextDetailDatas = (pagination) => {
        let current = pagination.current;
        this.detailTable = {
            ...this.detailTable,
            current: current
        };
        this.doDetailSearch({ current: current });
    }

    @action
    getIconInfo = (modeid) => {
        IndexAPI.getAppInfoByID({ modeid }).then((data: any) => {
            if (data.status == "1") {
                this.iconInfo = {
                    icon: data.icon || "icon-coms-ModelingEngine",
                    iconColor: data.iconColor || "#fff",
                    iconBg: data.iconBg || "#96358a"
                };
            }
        })
    }

    //获取主表字段变更信息
    showMainFieldLog=(viewlogid,billid)=>{
        if(this.isBackLog){
            this.baseParams.billid=billid;
        }
        API.getMainFieldLog({...this.baseParams,viewlogid,modeId:this.modeId}).then(({ api_status, api_errormsg,fieldDetail}) => {
            if (api_status) {
                this.mainLog_data=fieldDetail;
                this.mainLog_visible=true;
            } else {
                message.error(getLabel(383746, '请求失败') + "：" + api_errormsg)
            }
        });
    }
    //获取明细表字段变更信息
    showDetailFieldLog=(viewlogid,detailtable,billid)=>{
        if(this.isBackLog){
            this.baseParams.billid=billid;
        }
        const splitStr='  ,  ';
        API.getDetailFieldLog({...this.baseParams,viewlogid,modeId:this.modeId,detailtable}).then(({ api_status, api_errormsg,dataMap}) => {
            if (api_status) {
                this.detailLog_data=_.keys(dataMap).map(item=>{
                    let operateType;
                    let operateDesc='';
                    dataMap[item].forEach((element,index)=>{
                        if(index==0){
                            operateType=element.operateType;
                        }
                        if(operateType=='EDIT'){
                            operateDesc+=element.fieldlabel+getLabel(623, '由')+this.transValue(element.prefieldvalue)+getLabel(515395, '变更为')+this.transValue(element.fieldvalue)+splitStr;
                        }else if(operateType=='ADD'){
                            operateDesc+=element.fieldlabel+':'+this.transValue(element.fieldvalue)+splitStr;
                        }else if(operateType=='DEL'){
                            operateDesc+=element.fieldlabel+':'+this.transValue(element.prefieldvalue)+splitStr;
                        }
                    });
                    if(operateDesc.endsWith(splitStr)){
                        operateDesc=operateDesc.substring(0,operateDesc.length-5);
                    }
                    let operateTypeText="";
                    if(operateType=='ADD'){
                        operateTypeText=getLabel(1421, '新增');
                    }else if(operateType=='EDIT'){
                        operateTypeText=getLabel(93, '编辑');
                    }else if(operateType=='DEL'){
                        operateTypeText=getLabel(91, '删除');
                    }
                    return {id:item,operateType:operateTypeText,operateDesc};
                });
                this.detailLog_visible=true;
            } else {
                message.error(getLabel(383746, '请求失败') + "：" + api_errormsg)
            }
        });
    }

    transValue=(value)=>{
        if(value==''){
            return "<span style='color:green'>"+getLabel(15863, '空')+"</span>";
        }else{
            return "<span style='color:red'>"+value+"</span>";
        }
    }
}

export default new LogListStore();
